package com.baijiayun.live.ui.onlineuser

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.RecyclerView
import com.baijiayun.live.ui.R
import com.baijiayun.live.ui.base.BasePadFragment
import com.baijiayun.live.ui.base.getViewModel
import com.baijiayun.live.ui.chat.ChatOptMenuHelper
import com.baijiayun.live.ui.databinding.BjyPadLayoutItemOnlineUserBinding
import com.baijiayun.live.ui.isUserAdmin
import com.baijiayun.live.ui.users.group.GroupExtendableListViewAdapter
import com.baijiayun.live.ui.utils.ColorUtil
import com.baijiayun.livecore.context.LPConstants
import com.baijiayun.livecore.models.LPGroupItem
import com.baijiayun.livecore.models.LPUserModel
import com.baijiayun.livecore.models.imodels.IUserModel
import com.baijiayun.livecore.models.launch.LPAwardConfig
import com.baijiayun.livecore.utils.DisplayUtils
import com.baijiayun.liveuibase.utils.LinearLayoutWrapManager
import com.baijiayun.liveuibase.utils.ThemeDataUtil
import com.baijiayun.liveuibase.utils.drawable.DrawableBuilder
import com.baijiayun.liveuibase.widgets.dialog.AwardPopupWindow
import kotlinx.android.synthetic.main.fragment_pad_user_list.*

/**
 * Created by yongjiaming on 2019-10-23
 * Describe:
 */
class OnlineUserFragment : BasePadFragment() {

    private lateinit var onlineUserRecyclerView: RecyclerView
    private lateinit var onlineGroupTitleTv: TextView
    private lateinit var groupAdapter: GroupExtendableListViewAdapter

    private val onlineUserAdapter by lazy { OnlineUserAdapter() }

    private var onlineUserViewModel: OnlineUserViewModel? = null

    private val navigateToMainObserver by lazy {
        Observer<Boolean> {
            if (it == true) {
                initSuccess()
            }
        }
    }

    private var isLoading = false

    override fun init(view: View) {
        // do nothing
    }

    override fun getLayoutId() = R.layout.fragment_pad_user_list

    @SuppressLint("SetTextI18n")
    override fun observeActions() {
        routerViewModel.actionNavigateToMain.observeForever(navigateToMainObserver)
    }

    @SuppressLint("SetTextI18n")
    private fun initSuccess() {
        initExpandableListView()
        activity?.run {
            onlineUserViewModel = getViewModel { OnlineUserViewModel(routerViewModel.liveRoom) }
            onlineUserViewModel?.run {
                subscribe()
                onlineUserList.observe(this@OnlineUserFragment, Observer {
                    isLoading = false
                    onlineUserAdapter.notifyDataSetChanged()
                })
                onlineUserGroup.observe(this@OnlineUserFragment, Observer {
                    onlineGroupTitleTv.visibility = if (it.isNullOrEmpty()) View.GONE else View.VISIBLE
                    onlineGroupTitleTv.text = resources.getString(R.string.string_group) + "(${it?.size})"
                    groupAdapter.setData(it)
                    groupAdapter.notifyDataSetChanged()
                })
            }
        }

        routerViewModel.notifyAward.observe(this, Observer {
            onlineUserAdapter.notifyDataSetChanged()
            groupAdapter.notifyDataSetChanged()
        })
    }

    private fun initExpandableListView() {
        context?.let {
            onlineUserRecyclerView = RecyclerView(it)
            with(onlineUserRecyclerView) {
                layoutManager = LinearLayoutWrapManager(context)
                setHasFixedSize(true)
                onlineUserAdapter.setHasStableIds(true)
                adapter = onlineUserAdapter
            }
        }

        onlineGroupTitleTv = TextView(context)
        onlineGroupTitleTv.textSize = 16f
        onlineGroupTitleTv.setTextColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_window_main_text_color))
        onlineGroupTitleTv.height = DisplayUtils.dip2px(context, 30f)
        onlineGroupTitleTv.visibility = View.GONE

        val linearLayout = LinearLayout(context)
        linearLayout.orientation = LinearLayout.VERTICAL
        linearLayout.addView(onlineUserRecyclerView, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))
        linearLayout.addView(onlineGroupTitleTv)

        groupAdapter = GroupExtendableListViewAdapter(
            routerViewModel, onlineUserViewModel?.getAssistantLabel(), onlineUserViewModel?.getGroupId()
                ?: 0
        )
        groupAdapter.setOnUpdateListener { onlineUserViewModel?.loadMore(it) }
        elv_online_group.run {
            addHeaderView(linearLayout)
            setAdapter(groupAdapter)
            setOnGroupExpandListener {
                var i = 0
                val count = groupAdapter.groupCount
                while (i < count) {
                    if (i != it) {
                        elv_online_group.collapseGroup(i)
                    }
                    i++
                }

                val item = groupAdapter.getGroup(it) as LPGroupItem
                onlineUserViewModel?.updateGroupInfo(item)
            }
            setOnChildClickListener { _, view, groupPosition, childPosition, _ ->
                kotlin.run {
                    val userModel = groupAdapter.getChild(groupPosition, childPosition) as LPUserModel
                    ChatOptMenuHelper.showOptMenu(context, routerViewModel, view, userModel)
                    true
                }
            }
        }

        onlineUserAdapter.setOnItemClickListener(object : OnItemClickListener {
            override fun onItemClick(view: View, position: Int) {
                val user = onlineUserAdapter.getUser(position) as LPUserModel
                ChatOptMenuHelper.showOptMenu(context, routerViewModel, view, user)
            }
        })
    }


    inner class OnlineUserAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

        private val VIEW_TYPE_USER = 0
        private val VIEW_TYPE_LOADING = 1

        private var lastVisibleItem = 0
        private var totalItemCount = 0
        private var onItemClickListener: OnItemClickListener? = null

        init {
            onlineUserRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    if (dy > 0) {
                        val linearLayoutManager = recyclerView.layoutManager as LinearLayoutWrapManager
                        //LPLogger.d("user", "totalItemCount=$totalItemCount, lastVisibleItem=$lastVisibleItem")
                        totalItemCount = linearLayoutManager.itemCount
                        lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition()
                        if (!isLoading && lastVisibleItem == itemCount - 1) {
                            isLoading = true
                            onlineUserViewModel?.loadMore()
                            notifyDataSetChanged()
                        }
                    }
                }
            })
        }

        override fun getItemViewType(position: Int): Int {
            if (isLoading && position == itemCount - 1) {
                return VIEW_TYPE_LOADING
            }
            return VIEW_TYPE_USER
        }

        override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return if (viewType == VIEW_TYPE_LOADING) {
                val itemView = LayoutInflater.from(context).inflate(R.layout.bjy_item_online_user_loadmore, viewGroup, false)
                LoadingViewHolder(itemView)
            } else {
                val dataBinding: BjyPadLayoutItemOnlineUserBinding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.bjy_pad_layout_item_online_user, viewGroup, false)
                OnlineUserViewHolder(dataBinding, dataBinding.root)
            }
        }

        override fun getItemCount(): Int {
            if (isLoading) {
                return (onlineUserViewModel?.getCount() ?: 0) + 1
            }
            return onlineUserViewModel?.getCount() ?: 0
        }

        override fun getItemId(position: Int): Long {
            if (isLoading && position == itemCount - 1) {
                return -1L
            }
            return getUser(position).number.hashCode().toLong()
        }

        override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) {
            when (viewHolder) {
                is LoadingViewHolder -> {
                    viewHolder.progressBar.isIndeterminate = true
                }
                is OnlineUserViewHolder -> {
                    viewHolder.itemView.setOnClickListener {
                        onItemClickListener?.onItemClick(viewHolder.itemView, position)
                    }
                    val itemUser = getUser(position)
                    viewHolder.dataBinding.user = itemUser
                    when (itemUser.type) {
                        LPConstants.LPUserType.Teacher -> {
                            viewHolder.roleTextView.visibility = View.VISIBLE
                            viewHolder.roleTextView.text = if (TextUtils.isEmpty(routerViewModel.liveRoom.customizeTeacherLabel))
                                context?.resources?.getString(R.string.live_teacher) else routerViewModel.liveRoom.customizeTeacherLabel
                            viewHolder.roleTextView.setTextColor(context?.let { ThemeDataUtil.getColorFromThemeConfigByAttrId(it, R.attr.base_theme_live_product_color) }
                                ?: Color.BLACK)
                            viewHolder.roleTextView.background = context?.let {
                                DrawableBuilder()
                                    .cornerRadius(DisplayUtils.dip2px(it, 4f))
                                    .strokeWidth(DisplayUtils.dip2px(it, 1f))
                                    .strokeColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(it, R.attr.base_theme_live_product_color))
                                    .build()
                            }
                        }
                        LPConstants.LPUserType.Assistant -> {
                            val color = ColorUtil.getColor(itemUser.number)
                            viewHolder.dataBinding.itemOnlineUserAvatar.setCircleBackgroundColor(Color.HSVToColor(color))
                            viewHolder.roleTextView.visibility = View.VISIBLE
                            viewHolder.roleTextView.text = if (TextUtils.isEmpty(routerViewModel.liveRoom.customizeAssistantLabel))
                                context?.resources?.getString(R.string.live_assistent) else routerViewModel.liveRoom.customizeAssistantLabel
                            viewHolder.roleTextView.setTextColor(
                                context?.let { ContextCompat.getColor(it, R.color.live_pad_orange) }
                                    ?: Color.BLACK)
                            viewHolder.roleTextView.background = context?.let { ContextCompat.getDrawable(it, R.drawable.item_online_user_assistant_bg) }
                        }
                        else -> {
                            viewHolder.roleTextView.visibility = View.GONE
                        }
                    }
                    initAward(viewHolder.itemView.context, viewHolder, itemUser)
                    val userInfo = routerViewModel.awardRecord[itemUser.number]
                    val awardCount = userInfo?.count ?: 0
                    if (awardCount > 0) {
                        viewHolder.awardCount.text = awardCount.toString()
                    } else {
                        viewHolder.awardCount.text = ""
                    }
                    viewHolder.awardContainer.visibility = if (isUserAdmin(itemUser)) {
                        View.GONE
                    } else {
                        if (routerViewModel.liveRoom.currentUser.type == LPConstants.LPUserType.Student) {
                            if (awardCount > 0) {
                                View.VISIBLE
                            } else {
                                View.GONE
                            }
                        } else {
                            View.VISIBLE
                        }
                    }
                    viewHolder.awardContainer.setOnClickListener {
                        if (availableAward == null) {
                            awardPopupWindow!!.setUserModel(itemUser)
                            awardPopupWindow!!.show(it)
                        } else {
                            routerViewModel.routerListener?.requestAward(itemUser, availableAward!!.key)
                        }
                    }
                }
            }
        }

        private var awardPopupWindow: AwardPopupWindow? = null
        private var availableAward: LPAwardConfig? = null

        /**
         * 初始化 奖励 图标
         */
        private fun initAward(context: Context, viewHolder: OnlineUserViewHolder, itemUser: IUserModel) {
            val awardConfigs: Array<LPAwardConfig> = routerViewModel.liveRoom.awardConfigs
            var enableAwardTypeCount = 0
            var availableAward: LPAwardConfig? = null
            for (lpAwardConfig in awardConfigs) {
                if (lpAwardConfig.isEnable == 1) {
                    availableAward = lpAwardConfig
                    enableAwardTypeCount++
                }
            }
            if (enableAwardTypeCount <= 1 && availableAward != null) {
                // 仅一种启用，使用对应logo
                viewHolder.awardIcon.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.base_ic_award_like))
                this.availableAward = availableAward
            } else {
                // 使用钻石
                viewHolder.awardIcon.setImageResource(R.drawable.base_ic_video_award_default)
                this.availableAward = null
                awardPopupWindow = AwardPopupWindow(context) { user: IUserModel?, key: String? -> routerViewModel.routerListener?.requestAward(user, key) }
            }
        }

        fun getUser(position: Int): IUserModel {
            var user: IUserModel? = onlineUserViewModel?.getUser(position)
            if (user == null) {
                user = LPUserModel()
                user.userId = "0"
                user.number = "0"
            }
            return user
        }

        fun setOnItemClickListener(onItemClickListener: OnItemClickListener) {
            this.onItemClickListener = onItemClickListener
        }
    }


    override fun onDestroyView() {
        super.onDestroyView()
        routerViewModel.actionNavigateToMain.removeObserver(navigateToMainObserver)
        onlineUserRecyclerView.adapter = null
        onlineUserViewModel = null
    }

    interface OnItemClickListener {
        fun onItemClick(view: View, position: Int)
    }


    class LoadingViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var progressBar: ProgressBar = itemView.findViewById(R.id.item_online_user_progress)
    }

    class OnlineUserViewHolder(val dataBinding: BjyPadLayoutItemOnlineUserBinding, itemView: View) : RecyclerView.ViewHolder(itemView) {
        val roleTextView: TextView = itemView.findViewById(R.id.item_online_user_role)
        val awardContainer: View = itemView.findViewById(R.id.item_award_container)
        val awardCount: TextView = itemView.findViewById(R.id.item_award_count)
        val awardIcon: ImageView = itemView.findViewById(R.id.item_award_icon)

        init {
            awardContainer.background = DrawableBuilder()
                .cornerRadius(DisplayUtils.dip2px(itemView.context, 60f))
                .solidColor(ContextCompat.getColor(itemView.context, R.color.base_main_color_layer_20))
                .build()
        }
    }
}